// 导入全局Api管理
import { GET_ARTICLE_LIST } from "@/assets/api/api.js";

// 导入Axios拦截器
import instance from "@/axios_instance/axios_instance.js";

import CommentNumber from "@/components/comment_number/comment_number.vue";

export default {
  name: "HomeContent",
  components: {
    CommentNumber,
  },
  data() {
    return {
      // 文章列表
      articleList: []
    };
  },
  created() {
    this.getArticleList()
  },
  updated() {
    this.$nextTick(() => {
      this.loadJs("https://cy-cdn.kuaizhan.com/upload/plugins/plugins.list.count.js?clientId=cyvIv1VXi", function() {
        window.changyan
      });
    });
  },
  methods: {
    // 生成评论数 script 标签
    loadJs(url, cb) {
      try {
        const c =
          document.getElementsByTagName("head")[0] ||
          document.head ||
          document.documentElement;
        const b = document.createElement("script");
        // b.setAttribute("type", "text/javascript");
        // b.setAttribute("charset", "UTF-8");
        b.setAttribute("src", url);
        b.setAttribute("id", "cy_cmt_num");
        if (window.attachEvent) {
          b.onreadystatechange = function() {
            const e = b.readyState;
            if (e === "loaded" || e === "complete") {
              b.onreadystatechange = null;
              cb && cb();
            }
          };
        } else {
          if (cb) {
            b.onload = cb;
          }
        }
        c.appendChild(b);
      } catch (error) {
        cb && cb();
      }
    },

    // 获取文章列表
    getArticleList() {
      instance.get(GET_ARTICLE_LIST).then(res => {
        if (res.status == 200) {
          this.articleList = res.data
        }
      })
    },

    // 根据文章下标动态生成 class
    generateClassName(index) {
      return "ep-" + (index + 1);
    },

    // 跳转文章详情页面
    clickReading(id) {
      this.$router.push({ name: "ArticleContent", query: { id: id } });
    }
  },
  // 销毁 script 标签
  beforeDestroy() {
    try {
      const removeRep = /^http(s)?\:\/\/changyan\./;
      const $head =
        document.getElementsByTagName("head")[0] ||
        document.head ||
        document.documentElement;
      const $script = $head.querySelectorAll("script");

      console.log(removeRep);
      $script.forEach((item, index) => {
        const src = item.getAttribute("src");
        if (src && removeRep.test(src)) {
          $head.removeChild(item);
        }
      });
      for (const key in window) {
        if (/^(changyan(\d)?|cyan)/.test(key)) {
          window[key] = undefined;
        }
      }
    } catch (error) {}
  }
};
